//
//  HYOauthViewController.swift
//  iOSWeibo
//
//  Created by why on 16/7/19.
//  Copyright © 2016年 王浩宇. All rights reserved.
//

import UIKit
import SVProgressHUD

class HYOauthViewController: UIViewController {
    
    override func loadView() {
        self.view = webView
        
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.whiteColor()
        
        setupNavigationBar()
        
//        https://api.weibo.com/oauth2/authorize?client_id=3480088097&redirect_uri=http://baidu.com
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        
        // 显示加载
        SVProgressHUD.setMinimumDismissTimeInterval(2)
        
        SVProgressHUD.showWithStatus("正在加载...") // 进度一直转,只有dismiss才会关闭
    }
    
    private func setupNavigationBar() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        self.navigationItem.title = "登录"
    }
    
    @objc private func autoFill() {
        
        let jsCode = "document.getElementById('userId').value = '15113893854';document.getElementById('passwd').value = 'why729252257'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsCode)
    }
    
    @objc private func close() {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    private lazy var webView: UIWebView = UIWebView()

}

extension HYOauthViewController: UIWebViewDelegate {
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString
        print("加载的地址: \(urlString)")
        
        // 其他界面不需要拦截,只需要拦截授权回调地址
        // http://www.baidu.com/
        if !urlString.hasPrefix(redirect_uri) {
            // 不是授权回调地址, 放过,去加载
            return true
        } else {
            // 是授权回调地址
            // 取消: http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_
            // 授权: http://www.baidu.com/?code=8b222812bb9754a65e09f1d9bd4d5193
            
            // ?后面的东西成为query
            
            // 区分 取消按钮 和 授权按钮,看?后面是否以code=开头
            let query = request.URL!.query!
//            print("query: \(query)")
            // 判断query是否以code=开头
            let codeString = "code="
            if query.hasPrefix(codeString) {
                // 点击了授权
                print("点击了授权")
                // code=1d98d710a8288b23c8a0440bca0c846c
                // 截取code=后面那串字符串
                let nsQuery = query as NSString
                let code = nsQuery.substringFromIndex(codeString.characters.count)
//                print("截取到的code = \(code)")
//                self.loadAccessToken(code)
                
                HYUserAccountViewModel.sharedUserAccountViewModel.loadAccessToken(code, completion: { (error: NSError?) -> Void in
                    // 网络失败也调用
                    if error != nil {
                        SVProgressHUD.showErrorWithStatus("加载AccessToken出错了")
                        
                        // 延迟关闭
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            self.close()
                        })
                        return
                    }
                    
                    // 保存账号后会调用
                    // 关闭控制器
                    self.close()
                    
                    AppDelegate.switchRootViewController(HYWelcomeViewController())
                })
            } else {
                // 点击了取消
                self.close()
            }
            
            return false
        }
    }
    
//    private func loadAccessToken(code:String) {
//        let urlString = "https://api.weibo.com/oauth2/access_token"
//        
//        // 参数
//        let parameters = [
//            "client_id": client_id,
//            "client_secret": client_secret,
//            "grant_type": "authorization_code",
//            "code": code,
//            "redirect_uri": redirect_uri
//        ]
//        
//        // 使用AFN发送POST请求
//        HYNetworkTool.sharedInstance.POST(urlString, parameters: parameters, progress: nil, success: { (_, resopnseOjbect) -> Void in
////            print("resopnseOjbect: \(resopnseOjbect)")
//            
//            let dict = resopnseOjbect as! [String: AnyObject]
//            let userAccount = HYUserAccount(dict: dict)
//            
//            print("userAccount = \(userAccount)")
//            }) { (_, error) -> Void in
//                print("error: \(error)")
//        }
//    }
}
